package com.example.tao.smartcar.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tao.smartcar.BaseActivity;
import com.example.tao.smartcar.R;
import com.example.tao.smartcar.SmartCarApplication;

public class BluetoothScanActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {


    private static final int REQUEST_ENABLE_BLE = 1;

    private BluetoothAdapter mBluetoothAdapter;
    private ArrayAdapter<String> mDevicesArrayAdapter;

    private Button searchBtn;
    private ListView deviceListView;

    private Button skipBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_scan);
        SmartCarApplication.getInstance().addActivity(this);
        setToolbar("", false);
        initView();
    }

    private void initView() {
        searchBtn = (Button) this.findViewById(R.id.search_btn);
        searchBtn.setOnClickListener(this);

        skipBtn = (Button) this.findViewById(R.id.skip_btn);
        skipBtn.setOnClickListener(this);

        deviceListView = (ListView) this.findViewById(R.id.device);

        mDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name_item);

        deviceListView.setAdapter(mDevicesArrayAdapter);

        deviceListView.setOnItemClickListener(this);

        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mBLEReceiver, intentFilter);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "无法获取BLE设备", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BLE);
        }
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()) {
            case R.id.skip_btn :
                startActivity(new Intent(BluetoothScanActivity.this, TouchControlActivity.class));
                break;
            case R.id.search_btn :
                setToolbar("正在搜索设备...", false);
                mDevicesArrayAdapter.clear();
                if (mBluetoothAdapter.isDiscovering()) {
                    mBluetoothAdapter.cancelDiscovery();
                }
                mBluetoothAdapter.startDiscovery();
                break;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        mBluetoothAdapter.cancelDiscovery();

        String info = ((TextView)view).getText().toString();
        String deviceAddress = info.substring(info.length() - 17);

        Intent intent = new Intent(BluetoothScanActivity.this,OperationSettingActivity.class);
        intent.putExtra(OperationSettingActivity.EXTRAS_DEVICE_NAME, info);
        intent.putExtra(OperationSettingActivity.EXTRAS_DEVICE_ADDRESS, deviceAddress);
        startActivity(intent);
    }

    private final BroadcastReceiver mBLEReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                mDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setToolbar("选择要连接的设备", false);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }

        this.unregisterReceiver(mBLEReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_ENABLE_BLE && resultCode == Activity.RESULT_CANCELED) {
            finish();
            return;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
